//
//  PureTennisTabBarController.swift
//  puretennis
//
//  Created by IYE Technologies on 11/9/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit
class PureTennisTabBarController: UITabBarController {
    
    // Set tab bar item number
    let items = 4;
    
    let tabBarHeight:CGFloat = 75;

    var tabBarView:UIImageView!;
    
    var previousSelectedButton:CustomTabBarItemButton?;

    var navBarImage: UIImage = ImageUtils.stretchableImage("navbar");
    
    var customItems:[CustomTabBarItemButton] = [];
    
    override func viewDidLoad() {
        super.viewDidLoad();
        UIApplication.sharedApplication().statusBarHidden = false;
        
        self.tabBar.hidden = true;

        let newTabBarY = self.view.frame.height - tabBarHeight;
        
        self.tabBarView = UIImageView(frame: CGRect(x: 0, y: newTabBarY, width: self.view.frame.width, height: tabBarHeight));

        self.tabBarView.userInteractionEnabled = true;
        
        self.view.addSubview(tabBarView);

        var storyboard = UIStoryboard(name: "Main", bundle: nil)

        var groupViewNavController = createNavController(storyboard, viewId: "groupView")  as PureTennisNavigationController;
        self.creatTabBarItem("group_tabbar", selectImageName: "group_tabbar_checked", index: 0);
        
        var appointmentViewNavController = createNavController(UIStoryboard(name: "Appointment", bundle: nil), viewId: "appointmentAndAvailabilityView") as PureTennisNavigationController;
        self.creatTabBarItem("appointment_tabbar", selectImageName: "appointment_tabbar_checked", index: 1);
        
        var timeNavController = createNavController(UIStoryboard(name: "MyAvailability", bundle: nil), viewId: "MyAvailabilityView") as PureTennisNavigationController;
        self.creatTabBarItem("time_tabbar", selectImageName: "time_tabbar_checked", index: 2);
        
        var meNavController = createNavController(UIStoryboard(name: "Me", bundle: nil), viewId: "myDetailsView") as PureTennisNavigationController;
        self.creatTabBarItem("mein_tabbar", selectImageName: "mein_tabbar_checked", index: 3);
        
        setViewControllers([groupViewNavController, appointmentViewNavController, timeNavController,meNavController], animated: true)
        
        self.toggleView(self.customItems.first!);
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
    }
    
    func navigationControllerSupportedInterfaceOrientations(navigationController: UINavigationController) -> Int {
        return 0;
    }    

    func loadBadges(){
        var url = "/api/v1/badges"
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var badges = response as NSDictionary
            var group = badges.objectForKey("group") as Int;
            var groupTabBarItemButton = self.customItems[0];
            groupTabBarItemButton.setBadgeValue((group));
            var appointment = badges.objectForKey("appointment") as Int
            var appointmentTabBarItemButton = self.customItems[1];
            appointmentTabBarItemButton.setBadgeValue(appointment);
            }, errorHandle: { (error) -> Void in
                
        });
    }
  
    func updateBadge(){
        var selectedIndex = self.selectedIndex
        var item = currentTabBarItem();
        item.updateBadge();
    }

    func currentTabBarItem() -> CustomTabBarItemButton{
        var selectedIndex = self.selectedIndex
        return self.customItems[selectedIndex];
    }
    
    func createNavController(storyboard: UIStoryboard!, viewId: String!) -> UINavigationController{
        var viewController = storyboard.instantiateViewControllerWithIdentifier(viewId) as UIViewController;
        ViewUtils.addBackgroundView(viewController)
        var navController = PureTennisNavigationController(rootViewController: viewController);
        navController.navigationBar.backgroundColor = UIColor.clearColor();
        navController.navigationBar.setBackgroundImage(navBarImage, forBarMetrics: UIBarMetrics.Default);
        navController.navigationBar.shadowImage = UIImage();
        return navController;
    }

    func creatTabBarItem(normalImageName:String, selectImageName:String,index:Int) -> CustomTabBarItemButton{
        let itemWidth = (self.view.frame.width) / CGFloat(items);
        let itemHeight = self.tabBarView.frame.height;
        // Tab bar item start point
        let itemX = CGFloat(index) * itemWidth;
        
        let tabBarItem = CustomTabBarItemButton(frame: CGRectMake(itemX, 0, itemWidth, itemHeight));
        tabBarItem.tag = index;
        tabBarItem.setImage((UIImage(named: normalImageName)!), forState: UIControlState.Normal);
        tabBarItem.setImage((UIImage(named: selectImageName)!), forState: UIControlState.Disabled);
        tabBarItem.addTarget(self, action: Selector("toggleView:"), forControlEvents: UIControlEvents.TouchUpInside);
        self.tabBarView.addSubview(tabBarItem);
        self.customItems.append(tabBarItem);
        return tabBarItem;
    }
    
    func toggleView(sender:CustomTabBarItemButton){
        sender.enabled = false;
        if(previousSelectedButton != sender){
            self.selectedIndex = sender.tag;
            previousSelectedButton?.enabled = true;
        }
        previousSelectedButton = sender;
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning();
        Utils.debug("Memory warning")
    }
}
